import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;


public class MessageArea extends JPanel implements Observer {
	
	private User user;
	
	private JTextArea userArea;
	private JTextArea messageArea;
	private JTextArea timeArea;
	private String title = "Messaggi";
	
	private Color statusColor;
	
	public MessageArea(JPanel mainPanel ) {
		super();
		statusColor = ChatServer.statusColor;
		user = User.getUser();
		
		setBorder();
		setLayout(new BorderLayout(0,0));
		
		add( new Header(), BorderLayout.NORTH);
		
		JPanel scrollablePanel = new JPanel();
		scrollablePanel.setLayout( new BorderLayout(0,0) );
		
		
		userArea = new JTextArea( 1,user.getUserNameMaxDim() );
		userArea.setEditable(false);
		userArea.setAlignmentX(JTextArea.CENTER_ALIGNMENT);
		scrollablePanel.add(userArea, BorderLayout.WEST);
		
		messageArea = new JTextArea(25, 30);
		messageArea.setEditable(false);
		messageArea.setLineWrap(true);
		messageArea.setWrapStyleWord(true);
		
		scrollablePanel.add(messageArea, BorderLayout.CENTER);
		
		timeArea = new JTextArea(1,5);
		timeArea.setEditable(false);
		timeArea.setForeground(Color.GRAY);
		scrollablePanel.add(timeArea, BorderLayout.EAST);
		
		scrollablePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		JScrollPane scrollPane = new JScrollPane(scrollablePanel);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		add(scrollPane, BorderLayout.CENTER);
		mainPanel.add(this);
		
	}
	
	private void setBorder(){
		Border border = BorderFactory.createLineBorder(ChatServer.statusColor);
		setBorder( BorderFactory.createTitledBorder(border, title));
	}
	
	
	
	@Override
	public void update(Observable arg0, Object arg1) {
		InputMessagePanel.MessageInfo m = (InputMessagePanel.MessageInfo) arg1;
		userArea.append(" "+m.getUserName()+": \n");
		
		messageArea.append(m.getMessage()+"\n");
		timeArea.append(m.getMessageTime() + "\n");
		
	}
	
	private class Header extends JPanel{
		
		public Header() {
			super();
			Color bg = new Color(238,238,238);
			
			setLayout(new BorderLayout(0,0));
			
			JTextArea userNameSpace= new JTextArea(1, user.getUserNameMaxDim());
			userNameSpace.setText("User");
			userNameSpace.setEditable(false);
			userNameSpace.setBackground(bg);
			add(userNameSpace, BorderLayout.WEST);
			
			JTextArea message = new JTextArea("Message");
			message.setBackground(bg);
			message.setEditable(false);
			add(message, BorderLayout.CENTER);
			
			JTextArea time = new JTextArea("Time	");
			time.setEditable(false);
			time.setBackground(bg);
			add(time, BorderLayout.EAST);
		}
		
	}
	

}
